import java.util.*;

public class Text {
    public class TreeNode {
       int val;
       TreeNode left;
       TreeNode right;
       TreeNode() {}
       TreeNode(int val) { this.val = val; }
       TreeNode(int val, TreeNode left, TreeNode right) {
          this.val = val;
          this.left = left;
          this.right = right;
       }
    }
    public String tree2str(TreeNode root) {
        StringBuilder stringBuilder = new StringBuilder();
        creatTree(root,stringBuilder);
        return stringBuilder.toString();
    }
    public void creatTree(TreeNode root,StringBuilder str) {
        if(root == null) {
            return;
        }
        str.append(root.val);
        if(root.left != null) {
            str.append("(");
            creatTree(root.left,str);
            str.append(")");
        }else{
            if(root.right == null) {
                return;
            }else{
                str.append("()");
            }
        }
        if(root.right != null) {
            str.append("(");
            creatTree(root.right,str);
            str.append(")");
        }else{
            return;
        }
    }
    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> ret = new ArrayList<>();
        if(root == null) {
            return ret;
        }
        TreeNode cur = root;
        Deque<TreeNode> stack = new ArrayDeque<>();
        while(cur != null || !stack.isEmpty()) {
            while(cur != null){
                stack.push(cur);
                ret.add(cur.val);
                cur = cur.left;
            }
            TreeNode top = stack.pop();
            cur = top.right;
        }
        return ret;
    }
    public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> ret = new ArrayList<>();
        if(root == null) {
            return ret;
        }
        TreeNode cur = root;
        TreeNode prev = null;
        Deque<TreeNode> stack = new ArrayDeque<>();
        while(cur != null || !stack.isEmpty()) {
            while(cur != null) {
                stack.push(cur);
                cur = cur.left;
            }
            TreeNode top = stack.peek();
            if(top.right == null || top.right == prev) {
                prev = stack.pop();
                ret.add(top.val);

            }else{
                cur = top.right;
            }
        }
        return ret;
    }
}
